use crate::{engine::GameEngine, config::GameConfig};
use anyhow::Result;
use serde_json::Value;
use std::collections::HashMap;
use uuid::Uuid;

pub struct EngineAPI {
    pub engine: GameEngine,
    pub callbacks: HashMap<String, Box<dyn Fn(Value) -> Value>>,
}

impl EngineAPI {
    pub fn new(config: GameConfig) -> Result<Self> {
        let engine = GameEngine::new(config)?;
        Ok(Self {
            engine,
            callbacks: HashMap::new(),
        })
    }
    
    pub fn register_callback(&mut self, name: &str, callback: Box<dyn Fn(Value) -> Value>) {
        self.callbacks.insert(name.to_string(), callback);
    }
    
    pub fn execute_command(&mut self, command: &str, args: Value) -> Result<Value> {
        match command {
            "start" => {
                self.engine.run()?;
                Ok(Value::Bool(true))
            }
            "load_scene" => {
                if let Some(scene_name) = args.as_str() {
                    self.engine.scene_manager.switch_scene(scene_name);
                    Ok(Value::Bool(true))
                } else {
                    Err(anyhow::anyhow!("Invalid scene name"))
                }
            }
            "create_entity" => {
                let entity_name = args["name"].as_str().unwrap_or("NewEntity");
                let mut entity = crate::ecs::entity::Entity::new(entity_name);
                
                // 添加组件
                if let Some(components) = args["components"].as_object() {
                    for (comp_type, comp_data) in components {
                        self.add_component(&mut entity, comp_type, comp_data)?;
                    }
                }
                
                // 添加到当前场景
                if let Some(scene) = self.engine.scene_manager.scenes.get_mut(&self.engine.scene_manager.current_scene) {
                    let entity_id = entity.id.clone(); // 先复制 ID
                    scene.add_entity(entity);
                    Ok(Value::String(entity_id.to_string()))
                } else {
                    Err(anyhow::anyhow!("No active scene"))
                }
            }
            _ => {
                if let Some(callback) = self.callbacks.get(command) {
                    Ok(callback(args))
                } else {
                    Err(anyhow::anyhow!("Unknown command: {}", command))
                }
            }
        }
    }
    
    fn add_component(&self, entity: &mut crate::ecs::entity::Entity, comp_type: &str, data: &Value) -> Result<()> {
        match comp_type {
            "Position" => {
                let x = data["x"].as_i64().unwrap_or(0) as i32;
                let y = data["y"].as_i64().unwrap_or(0) as i32;
                entity.add_component(components::Position { x, y });
            }
            "Stats" => {
                let health = data["health"].as_i64().unwrap_or(100) as i32;
                let max_health = data["max_health"].as_i64().unwrap_or(100) as i32;
                entity.add_component(components::Stats { health, max_health });
            }
            // 添加更多组件类型...
            _ => return Err(anyhow::anyhow!("Unknown component type: {}", comp_type)),
        }
        Ok(())
    }
    
    pub fn get_engine_state(&self) -> Value {
        let mut state = serde_json::json!({});
        
        // 添加场景信息
        state["current_scene"] = Value::String(self.engine.scene_manager.current_scene.clone());
        
        // 添加实体信息
        if let Some(scene) = self.engine.scene_manager.scenes.get(&self.engine.scene_manager.current_scene) {
            let entities = scene.entities.values().map(|e| {
                serde_json::json!({
                    "id": e.id.to_string(),
                    "name": e.name,
                    "components": self.get_entity_components(e)
                })
            }).collect::<Vec<_>>();
            state["entities"] = Value::Array(entities);
        }
        
        state
    }
    
    fn get_entity_components(&self, entity: &crate::ecs::entity::Entity) -> Value {
        let mut components = serde_json::json!({});
        
        if let Some(pos) = entity.get_component::<components::Position>() {
            components["Position"] = serde_json::json!({
                "x": pos.x,
                "y": pos.y
            });
        }
        
        if let Some(stats) = entity.get_component::<components::Stats>() {
            components["Stats"] = serde_json::json!({
                "health": stats.health,
                "max_health": stats.max_health
            });
        }
        
        components
    }
}

// 组件定义
pub mod components {
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct Position {
        pub x: i32,
        pub y: i32,
    }
    
    #[derive(serde::Serialize, serde::Deserialize)]
    pub struct Stats {
        pub health: i32,
        pub max_health: i32,
    }
}